import { Outlet } from "react-router";
import { Minimize, Close, Settings } from "@mui/icons-material";
import logo from "@/assets/logo.ico";
import { Badge, Box, IconButton, type SxProps } from "@mui/material";
import theme from "@/config/theme";
import { Window } from "@tauri-apps/api/window";
import { routes } from "@/config/routes";
import { getName } from "@tauri-apps/api/app";
import { type CSSProperties } from "react";
import { useStore } from "@/store/context";

function AppTitleBar({ title, navSettings }: { title: string; navSettings: () => void }) {
  const window = new Window("main");
  const { state } = useStore();
  const btnGroup = (
    <>
      <Badge overlap="circular" color="error" variant="dot" invisible={!state.hasUpdate}>
        <IconButton aria-label="delete" color="inherit" onClick={navSettings} size="small">
          <Settings fontSize="inherit" />
        </IconButton>
      </Badge>

      <IconButton
        aria-label="Minimize"
        color="inherit"
        size="small"
        onClick={() => window.minimize()}
      >
        <Minimize fontSize="inherit" />
      </IconButton>
      <IconButton aria-label="Close" color="inherit" size="small" onClick={() => window.close()}>
        <Close fontSize="inherit" />
      </IconButton>
    </>
  );

  const appTitleBarStyles: SxProps = {
    userSelect: "none",
    width: "100%",
    height: theme.titleBarHeight,
    backgroundColor: theme.titleBarColor,
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    color: "white",
    px: 1
  };

  const appTitleStyle: SxProps = {
    display: "flex",
    alignItems: "center",
    gap: "8px",
    fontSize: theme.titleBarTitleFontSize
  };

  const logoStyle: CSSProperties = {
    width: theme.titleBarLogoSize,
    height: theme.titleBarLogoSize
  };

  const appTitleBarBtnStyles: SxProps = {
    display: "flex",
    justifyContent: "center",
    justifyItems: "center"
  };

  return (
    <Box data-tauri-drag-region sx={appTitleBarStyles}>
      <Box sx={appTitleStyle}>
        <img style={logoStyle} src={logo} />
        {title}
      </Box>

      <Box sx={appTitleBarBtnStyles}>{btnGroup}</Box>
    </Box>
  );
}

export default function AppLayout() {
  const navigate = useNavigate();
  const [title, setTitle] = useState("");

  useEffect(() => {
    getName().then((name) => {
      setTitle(name);
    });
  }, []);

  return (
    <Box
      sx={{
        width: "100vw",
        height: "100vh",
        display: "flex",
        flexDirection: "column",
        justifyContent: "start"
      }}
    >
      <AppTitleBar
        title={title}
        navSettings={() => {
          navigate(routes.settings);
        }}
      />

      <Box sx={{ display: "flex", flexDirection: "column", flex: 1, overflow: "hidden" }}>
        <Outlet />
      </Box>
    </Box>
  );
}
